<template>
  <div class="container" style="margin-top: 50px; margin-bottom: 50px;">
    <el-card shadow="always">
      <el-container>
        <el-aside>
          <MemberMenu/>
        </el-aside>
        <el-main>
          <el-row type="flex" justify="end">
            <el-col :span="6">
              <el-tooltip class="item" effect="dark" content="编辑信息后记得点击此处保存哦~" placement="top">
                <el-switch
                    v-model="editable"
                    active-color="#13ce66"
                    active-text="编辑模式"
                    @change="handleEditChange"
                    inactive-text="查看模式">
                </el-switch>
              </el-tooltip>
            </el-col>
          </el-row>
          <el-form
              ref="registerForm"
              :rules="registerFormRules"
                   :model="basicForm"
                   label-width="100px">
            <el-card shadow="hover" class="mt-space">
              <el-descriptions title="会员信息" :colon=false :column="2">
                <el-descriptions-item>
                  <el-form-item label="会员等级">
                    <span style="color: #409EFF;">{{mlevelFormatter(basicForm.mlevel)}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="积分">
                    <span style="color: #409EFF;">{{basicForm.score}}</span>
                  </el-form-item>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
            <el-card shadow="hover" class="mt-space">
              <el-descriptions title="用户信息" :colon=false :column="2">
                <el-descriptions-item>
                  <el-form-item label="中文姓">
                    <el-input v-if="editable" v-model="basicForm.firstNameCn"></el-input>
                    <span v-else class="detail-info">{{basicForm.firstNameCn}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="中文名">
                    <el-input v-if="editable" v-model="basicForm.lastNameCn"></el-input>
                    <span v-else class="detail-info">{{basicForm.lastNameCn}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="英文姓">
                    <el-input v-if="editable" v-model="basicForm.firstNameEn"></el-input>
                    <span v-else class="detail-info">{{basicForm.firstNameEn}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="英文名">
                    <el-input v-if="editable" v-model="basicForm.lastNameEn"></el-input>
                    <span v-else class="detail-info">{{basicForm.lastNameEn}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="职业">
                    <el-select v-if="editable" v-model="basicForm.occupationClass" placeholder="请选择">
                      <el-option
                          v-for="item in dict.type.occupation_class"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                    <span v-else class="detail-info">{{occupationClassFormatter(basicForm.occupationClass)}}</span>
                  </el-form-item>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <el-card shadow="hover" class="mt-space">
              <el-descriptions title="实名信息" :colon=false :column="2">
                <el-descriptions-item>
                  <el-form-item label="证件类型">
                    <el-select v-if="editable" v-model="basicForm.idType" placeholder="请选择">
                      <el-option
                          v-for="item in dict.type.id_type"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                    <span v-else class="detail-info">{{idTypeFormatter(basicForm.idType)}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="证件号码">
                    <el-input v-if="editable" v-model="basicForm.idCardNumber"></el-input>
                    <span v-else class="detail-info">{{basicForm.idCardNumber}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="证件有效期">
                    <el-date-picker
                        v-if="editable"
                        v-model="basicForm.idDueDate"
                        type="date"
                        placeholder="选择日期">
                    </el-date-picker>
                    <span v-else class="detail-info">{{basicForm.idDueDate}}</span>
                  </el-form-item>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>

            <el-card shadow="hover" class="mt-space">
              <el-descriptions title="联系方式" :colon=false :column="2">
                <el-descriptions-item>
                  <el-form-item label="手机号码">
                    <el-input v-if="editable" v-model="basicForm.telephoneNumber"></el-input>
                    <span v-else class="detail-info">{{basicForm.telephoneNumber}}</span>
                  </el-form-item>
                </el-descriptions-item>
                <el-descriptions-item>
                  <el-form-item label="电子邮箱">
                    <el-input v-if="editable" v-model="basicForm.email" :readonly=true>
                      <template slot="append">
                        <el-link class="text-info" @click="handlerDialog" style="cursor: pointer">更换</el-link>
                      </template>
                    </el-input>
                    <span v-else class="detail-info">{{basicForm.email}}</span>
                  </el-form-item>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-form>
        </el-main>
      </el-container>
    </el-card>

    <el-dialog @close="reset" width="600px" title="更换邮箱" :visible.sync="dialogFormVisible">
      <el-steps :active="step" simple>
        <el-step title="验证旧邮箱" icon="el-icon-edit"></el-step>
        <el-step title="设置新邮箱" icon="el-icon-upload"></el-step>
      </el-steps>
      <div style="padding: 20px;" v-if="step == 1">
        <el-form>
          <el-form-item :label="'通过邮箱号：' + basicForm.email + '接收邮箱验证码'">
            <el-input v-model="emailBody.inputAuthCode" placeholder="请输入邮箱验证码">
              <template slot="append">
                <el-button @click="handleSendAuthCode(user.email)">{{btnText}}</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div style="padding: 20px;" v-if="step == 2">
        <el-form :label-position="labelPosition" :model="emailBody">
          <el-form-item>
            <el-input placeholder="新邮箱" v-model="emailBody.newEmail"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input placeholder="请输入邮箱验证码" v-model="emailBody.inputAuthCode">
              <template slot="append">
                <el-button @click="handleSendAuthCode(emailBody.newEmail)">{{btnText}}</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <div v-if="step == 1">
          <el-button type="primary" @click="changeEmailFirst(user.email)">下一步</el-button>
        </div>
        <div v-if="step == 2">
          <el-button type="primary" @click="changeEmailLast(user.email)">确 定</el-button>
        </div>
        </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {updateInfoSelf, verifyAuthCode, changeEmail, getMemberInfo} from "@/api/member/member";
import {getDictData, sendAuthCode} from "@/api/common";
import MemberMenu from "@/views/components/MemberMenu";

export default {
  name: 'memberCenter',
  dicts: ['member_type', 'id_type', 'occupation_class'],
  components: {MemberMenu},
  data() {
    return {
      btnText: '获取验证码',
      coldDownInterval: null,
      coldDown: 60,
      getVerificationCodeLoading: false,
      // 步骤
      step: 1,
      // 是否可编辑
      editable: false,
      // 基本信息表单
      basicForm: {
        firstNameCn: '',
        lastNameCn: '',
        firstNameEn: '',
        lastNameEn: '',
        occupationClass: '',
        idType: '',
        idCardNumber: '',
        idDueDate: new Date(),
        telephoneNumber: '',
        email: ''
      },
      loading: false,
      basicInfo: {},
      emailBody: {
        oldEmail: "",
        inputAuthCode: "",
        newEmail: "",
      },
      dialogFormVisible: false,
      labelPosition: 'right',
      sendEmailBtn: "获取验证码",
      btnBoolean: false,
      countDown: null,
      registerFormRules: {
        firstNameCn: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入姓（中文）",
          },
        ],
        lastNameCn: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入名（中文）",
          },
        ],
        firstNameEn: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入姓（英文）",
          },
        ],
        lastNameEn: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入名（英文）",
          },
        ],
        email: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入邮箱",
          },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        idCardNumber: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入身份证号",
          },
          {
            pattern:
                /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i,
            message: "请输入正确的身份证号码格式",
            trigger: ["blur", "change"],
          },
        ],
        idDueDate: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择证件有限期",
          },
        ],
        verificationCode: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入验证码",
          },
        ],
        mPassword: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入登录密码",
          },
        ],
        mRePassword: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请再次输入登录密码",
          },
        ],
        telephoneNumber: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入手机号",
          },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: ["blur", "change"],
          },
        ],
        occupationClass: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择职业类别",
          },
        ],
      }
    };
  },
  created() {
  },
  mounted() {
    let that = this;
    // 获取职业类别字典数据
    getDictData("occupation_class").then((res) => {
      that.occupationClassList = res.data;
    }).then(() => {
      getMemberInfo().then(res => {
        this.basicForm = res.data
      })
    })
  },
  computed: {
    ...mapGetters(["token", "user"])
  },
  methods: {
    // 清除计时器
    clearInteval() {
      if (this.coldDownInterval) {
        clearInterval(this.coldDownInterval)
        this.btnText = '获取验证码'
        this.getVerificationCodeLoading = false
      }
    },
    // 证件类型格式化器
    idTypeFormatter(val) {
      return this.selectDictLabel(this.dict.type.id_type, val)
    },
    // 会员职业格式化器
    occupationClassFormatter(val) {
      return this.selectDictLabel(this.dict.type.occupation_class, val)
    },
    // 会员等级格式化器
    mlevelFormatter(val) {
      return this.selectDictLabel(this.dict.type.member_type, val)
    },
    // 编辑模式变更事件
    handleEditChange(val) {
      if (!val) {
        this.updateInfoSelf('registerForm')
      }
    },
    // 身份证号格式化器
    idNumberFormatter(val) {
      if (null != val && ""!= val){
        return val.substring(0, 3) + '***********' + val.substring(14)
      }
    },
    // 会员信息修改
    updateInfoSelf(formName) {
      this.$refs[formName].validate((vaild) => {
        if (vaild) {
          this.loading = true,
              updateInfoSelf(this.basicForm).then((res) => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                }),
                    this.dialogFormVisible = false
              }).finally(() => {
                this.loading = false
              });
        }
      })
    },
    handlerDialog() {
      this.dialogFormVisible = true
    },
    /* 发送邮箱验证码 */
    handleSendAuthCode(email) {
      this.coldDown = 60
      let that = this
      sendAuthCode(email).then((res) => {
        that.coldDownInterval = setInterval(function () {
          if (that.coldDown < 1) {
            that.getVerificationCodeLoading = false
            clearInterval(that.coldDownInterval)
            that.btnText = '获取验证码'
          } else {
            that.coldDown--
            that.btnText = that.coldDown + "s"
          }
        }, 1000);
      })
    },
    // 更换邮箱第一步 验证原邮箱验证码
    changeEmailFirst(email) {
      this.clearInteval()
      this.emailBody.oldEmail = email;
      verifyAuthCode(this.emailBody).then((res) => {
        if (res.code == 200) {
          this.emailBody.inputAuthCode = null;
          this.sendEmailBtn = "获取验证码";
          this.btnBoolean = false;
          this.step++
        }
      })
    },
    // 更换邮箱第二部 验证新邮箱验证码
    changeEmailLast(email) {
      this.emailBody.oldEmail = email;
      changeEmail(this.emailBody).then((res) => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        getMemberInfo().then(res => {
          this.basicForm = res.data
          this.dialogFormVisible = false
        })
      })
    },
    // 邮箱更换的表单重置
    reset() {
      this.emailBody.inputAuthCode = null;
      this.emailBody.oldEmail = null;
      this.emailBody.newEmail = null;
    },
  }
};
</script>

<style lang="scss" scoped>
.mt-space {
  margin-top: 20px;
}

.detail-info {
  color: #909399;
}
</style>
